//
//  TSTaskSearchViewController.m
//  chart
//
//  Created by xu on 15/8/16.
//  Copyright (c) 2015年 xu. All rights reserved.
//

#import "TSTaskSearchViewController.h"
#import "TSDatePickerTextField.h"
#import "TSToolBarTextField.h"
#import "TSPickerTextField.h"
#import "TSMsgSearchResultTableViewController.h"
#import "TSMsgContentItemCell.h"
#import "TSMutipleCheckTableViewController.h"
#import "TSColor.h"

#define SEARCH_LABEL_WIDTH  100.f
#define SEARCH_LABEL_HEIGHT 35.f
#define SEARCH_ROW_GAP 10.f

@interface TSTaskSearchViewController ()<UITextViewDelegate>

@end

@implementation TSTaskSearchViewController{
    TSDatePickerTextField *startTimePickerTextField;
    TSDatePickerTextField *endTimePickerTextField;
    TSToolBarTextField *sectionTextField;
    TSPickerTextField *typePickerTextField;
    TSToolBarTextField *keywordTextField;
    UIScrollView *scrollView;
    NSMutableArray *selectedSectionIds;
    NSMutableArray *selectedUserIds;
}

@synthesize isJournal;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentViewController:) name:TSNotification_PresentViewController object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMultipleSelectCompelete:) name:TSNotification_OnMultipleSelectCompelete object:nil];
    
    self.navigationItem.title = isJournal?@"日程查询":@"任务查询";
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, currentDeviceWidth,currentDeviceHeight-NAV_AND_STATUS_BAR_HEIGHT)];
    scrollView.contentSize = CGRectMake(0, 0, currentDeviceWidth, currentDeviceHeight-NAV_AND_STATUS_BAR_HEIGHT+1).size;
    scrollView.scrollEnabled=YES;
    [self.view addSubview:scrollView];
    [self addTapGesture];
    
    [self addTimeRow];
    
    [self addSectionRow];
    
    if (!isJournal) {
        [self addTypeRow];
    }
    
    [self addKeyworkRow];
    
    [self addSearchBtn];
    
    keywordTextField.delegate = self;
}

- (void)presentViewController:(NSNotification *)noti
{
    NSNumber *type = noti.object;
    
    TSMutipleCheckTableViewController *multiple_vc = [[TSMutipleCheckTableViewController alloc] init];
    multiple_vc.toolBarTextFieldType = type.integerValue;
    TSBaseNavigationController *nav = [[TSBaseNavigationController alloc] initWithRootViewController:multiple_vc];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)onMultipleSelectCompelete:(NSNotification *)noti
{
    NSArray *names = [noti.object objectForKey:TSDictionaryKeyDefine_Name];
    NSNumber *type  = (NSNumber *)[noti.object objectForKey:TSDictionaryKeyDefine_Type];
    
    if (type.integerValue == ToolBarTextField_Type_Section) {
        [sectionTextField setText:[self getNames:names]];
    }
}

- (NSString *)getNames:(NSArray *)names
{
    NSMutableString *name_str = [[NSMutableString alloc] initWithString:@""];
    selectedSectionIds = [[NSMutableArray alloc] initWithCapacity:1];
    if (names && names.count > 0) {
        
        for (int i=0; i<names.count; i++) {
            TSUserModel *model = [names objectAtIndex:i];
            [name_str appendString:model.name];
            [selectedSectionIds addObject:model.userId];
            
            if (i < names.count-1) {
                [name_str appendString:@","];
            }
        }
    }
    
    return name_str;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)addTapGesture
{
    /* 加入收键盘手势 */
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleField:)];
    [self.view addGestureRecognizer:tap];
}

/* 隐藏键盘 */
- (void)handleField:(UIGestureRecognizer*)gesture{
    for (UIView * view in self.view.subviews) {
        if ([view isFirstResponder]) {
            [view resignFirstResponder];
        }
    }
}

- (UILabel *)createLabel:(CGRect)frame Title:(NSString *)title
{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    [label setText:title];
    [label setFont:FONT(12.f)];
    
    return label;
}

- (void)addTimeRow
{
    UILabel *startL_label = [self createLabel:CGRectMake(MARGIN_LEFT, MARGIN_TOP, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"开始时间:"];
    [scrollView addSubview:startL_label];
    
    startTimePickerTextField = [[TSDatePickerTextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(startL_label.frame)+10.f, MARGIN_TOP, currentDeviceWidth-MARGIN_LEFT*2-SEARCH_LABEL_WIDTH-10.f, SEARCH_LABEL_HEIGHT)];
    startTimePickerTextField.layer.borderWidth = 1.f;
    [scrollView addSubview:startTimePickerTextField];
    
    UILabel *end_label = [self createLabel:CGRectMake(MARGIN_LEFT, CGRectGetMaxY(startL_label.frame)+SEARCH_ROW_GAP, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"结束时间:"];
    [scrollView addSubview:end_label];
    endTimePickerTextField = [[TSDatePickerTextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(end_label.frame)+10.f, CGRectGetMinY(end_label.frame), CGRectGetWidth(startTimePickerTextField.frame), SEARCH_LABEL_HEIGHT)];
    endTimePickerTextField.layer.borderWidth = 1.f;
    [scrollView addSubview:endTimePickerTextField];
}

- (void)addSectionRow
{
    UILabel *label = [self createLabel:CGRectMake(MARGIN_LEFT, CGRectGetMaxY(endTimePickerTextField.frame)+SEARCH_ROW_GAP, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"部门:"];
    [scrollView addSubview:label];
    
    sectionTextField = [[TSToolBarTextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label.frame)+10.f, CGRectGetMinY(label.frame), CGRectGetWidth(startTimePickerTextField.frame), SEARCH_LABEL_HEIGHT)];
    [sectionTextField setToolBarTextFieldType:ToolBarTextField_Type_Section];
    [sectionTextField setNotShowKeyboard:YES];
    sectionTextField.layer.borderWidth = 1.f;
    [scrollView addSubview:sectionTextField];
}

- (void)addTypeRow
{
    UILabel *label = [self createLabel:CGRectMake(MARGIN_LEFT, CGRectGetMaxY(sectionTextField.frame)+SEARCH_ROW_GAP, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"类型:"];
    [scrollView addSubview:label];
    
    typePickerTextField = [[TSPickerTextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label.frame)+10.f, CGRectGetMinY(label.frame), CGRectGetWidth(startTimePickerTextField.frame), SEARCH_LABEL_HEIGHT) WithSourceArray:@[@"接收消息", @"发送消息", @"个人日程"]];
    typePickerTextField.layer.borderWidth = 1.f;
    [scrollView addSubview:typePickerTextField];
}

- (void)addKeyworkRow
{
    CGFloat height = CGRectGetMaxY(sectionTextField.frame)+SEARCH_ROW_GAP;
    if (!isJournal) {
        height = CGRectGetMaxY(typePickerTextField.frame)+SEARCH_ROW_GAP;
    }
    UILabel *label = [self createLabel:CGRectMake(MARGIN_LEFT, height, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"关键字:"];
    [scrollView addSubview:label];
    
    keywordTextField = [[TSToolBarTextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label.frame)+10.f, CGRectGetMinY(label.frame), CGRectGetWidth(startTimePickerTextField.frame), SEARCH_LABEL_HEIGHT)];
    keywordTextField.layer.borderWidth = 1.f;
    [scrollView addSubview:keywordTextField];
}

- (void)addSearchBtn
{
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(MARGIN_LEFT, CGRectGetMaxY(keywordTextField.frame)+SEARCH_ROW_GAP, currentDeviceWidth-2*MARGIN_LEFT, SEARCH_LABEL_HEIGHT)];
    [btn setTitle:@"查询" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(onSearchBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundColor:[TSColor mainColor]];
    [btn.layer setCornerRadius:5.f];
    [btn.titleLabel setFont:FONT(12.f)];
    [scrollView addSubview:btn];
}

- (void)onSearchBtnClick:(UIButton *)sender
{
    TSMsgSearchResultTableViewController *search_result_vc = [[TSMsgSearchResultTableViewController alloc] init];
    search_result_vc.type =[self getType];
    [search_result_vc setUrl:[self getUrlByType] StartDate:startTimePickerTextField.text EndTime:endTimePickerTextField.text Keywords:keywordTextField.text SectionIds:[self getSectionIds]];
    [self.navigationController pushViewController:search_result_vc animated:YES];
}

- (NSString *)getSectionIds
{
    NSMutableString *str = [[NSMutableString alloc] initWithString:@""];
    if (selectedSectionIds && selectedSectionIds.count > 0) {
        
        int i=0;
        for (NSString *item_id in selectedSectionIds) {
            [str appendString:item_id];
            
            if (i < selectedSectionIds.count-1) {
                [str appendString:@","];
            }
            
            i++;
        }
    }
    
    return  str;
}

- (NSString *)getUrlByType
{
    if (typePickerTextField) {
        if ([typePickerTextField.text isEqualToString:@"接收消息"]) {
            return kRequestUrl_SendMessage_outList_message_selectReceive;
        }
        else if([typePickerTextField.text isEqualToString:@"发送消息"]){
            return kRequestUrl_SendMessage_outList_message_selectSend;
        }
        else if([typePickerTextField.text isEqualToString:@"个人日程"]){
            return kRequestUrl_SendMessage_outList_journal_select;
        }
    }
    
    return @"";
}

- (NSInteger)getType
{
    if (typePickerTextField) {
        if ([typePickerTextField.text isEqualToString:@"接收消息"]) {
            return 0;
        }
        else if([typePickerTextField.text isEqualToString:@"发送消息"]){
            return 1;
        }
        else if([typePickerTextField.text isEqualToString:@"个人日程"]){
            return 2;
        }
    }
    return 0;
}


- (void)textViewDidBeginEditing:(UITextView *)textView{
    CGFloat textFieldFromTop =  textView.frame.origin.y;
    CGFloat offset = textFieldFromTop-currentDeviceHeight+NAV_AND_STATUS_BAR_HEIGHT +316;
    if(offset>0){
        [scrollView setContentOffset:CGPointMake(0, offset)];
    }

}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    [scrollView setContentOffset:CGPointMake(0, 0)];

}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
